导航菜单
首页 >  Multer Easily upload files with Nodejs and Express  > File Uploads with Express.js: A Step

File Uploads with Express.js: A Step

Before we start, make sure you have Node.js and npm installed on your system. You can check if you have them installed by running the following commands in your terminal:

node -vnpm -v

If you don’t have Node.js and npm installed, you can download them from the official website (https://nodejs.org/) and follow the instructions to install them on your system.

Now, let’s start by creating a new Node.js project. Open your terminal and navigate to the directory where you want to create the project. Then run the following command to create a package.json file:

npm init -y

This will create a package.json file with default values. Next, we need to install Express.js. Run the following command to install it:

npm install express

This will install Express.js and add it to the dependencies section in the package.json file.

Now that we have all the required dependencies installed, let’s create the server. Create a file named “server.js” and add the following code to it:

const express = require('express');const app = express();app.listen(3000, () => { console.log('Server listening on port 3000');});

This code creates an Express.js server and listens for incoming requests on port 3000. You can change the port number to any other available port if you wish.

Next, we need to set up the route for handling file uploads. Add the following code to the server.js file:

app.post('/upload', (req, res) => { // handle file upload here});

This code creates a POST route at the ‘/upload’ path, which will handle the file upload.

To handle the file upload, we need to install a middleware called “multer”. Multer is a middleware that allows you to handle HTTP requests with enctype “multipart/form-data”, which is used for file uploads. Run the following command to install it:

npm install multer

Now that we have multer installed, let’s use it to handle the file upload. Add the following code to the ‘/upload’ route:

const multer = require('multer');const storage = multer.diskStorage({ destination: (req, file, cb) => { // specify where the uploaded files should be stored cb(null, 'uploads/'); }, filename: (req, file, cb) => { // specify a unique file name for the uploaded file cb(null, file.originalname); }});// create a multer instance with the specified storage settingsconst upload = multer({ storage });// create a POST route for file uploadsapp.post('/upload', upload.single('file'), (req, res) => { // check if a file was uploaded if (!req.file) { // if no file was uploaded, send an error response return res.send({ success: false, message: 'No file was uploaded' }); } // if a file was uploaded, send a success response return res.send({ success: true, message: 'File was uploaded successfully' });});

Great! Now that we have set up the file upload route and configured multer to handle the file upload, let’s move on to the next step: processing the uploaded file.

Inside the ‘/upload’ route, add the following code to process the uploaded file:

if (req.file) { // file was uploaded return res.send({ success: true, message: 'File was uploaded successfully' });}

This code checks if a file was uploaded and sends a response with a success message if it was.

Finally, we need to create an HTML form for the user to select and upload a file. Create an “index.html” file in the root directory of the project and add the following code to it:

Upload

This is a simple HTML form with a file input field and a submit button. The form action is set to ‘/upload’, which is the route we created earlier to handle the file upload. The enctype attribute is set to “multipart/form-data”, which is required for file uploads.

That’s it! You now have a simple file upload system using Express.js. To test it out, start the server by running the following command in the terminal:

node server.js

Then, open your web browser and go to http://localhost:3000. You should see the file upload form. Select a file and click the “Upload” button to upload it. The uploaded file will be saved in the “uploads” directory.

相关推荐: